package itsm.isperp.module.controller.api.mobile;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.domain.IUser;
import itsm.isperp.framework.utils.JsonBuilder;
import itsm.isperp.framework.utils.Pair;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.controller.incident.IcdIncidentController;
import itsm.isperp.module.entity.app.AppDict;
import itsm.isperp.module.entity.incident.IcdIncident;
import itsm.isperp.module.entity.incident.IcdIncidentHandleProcess;
import itsm.isperp.module.service.app.AppDictService;
import itsm.isperp.module.service.app.AppUserService;
import itsm.isperp.module.service.configuration.ConfCiUseRelationService;
import itsm.isperp.module.service.incident.IcdIncidentHandleProcessService;
import itsm.isperp.module.service.incident.IcdIncidentService;
import itsm.isperp.module.service.slm.SlmServiceTargetService;
import itsm.isperp.workflow.dto.BpmTransitionLine;
import itsm.isperp.workflow.service.BpmProcessRunService;
import itsm.isperp.workflow.utils.BpmConst;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 
 * 手机端事件接口控制器
 * 
 * @author zhouhg
 * @date 2014-3-25
 * @since 1.0
 * 
 */
@Controller
@RequestMapping("api/mobile/incident")
public class MobileIncidentController {

	public static final Logger logger = LoggerFactory
			.getLogger(MobileIncidentController.class);

	@Autowired
	IcdIncidentService icdIncidentService;

	/**
	 * 获取待办事件列表
	 * 
	 * @param username
	 * @param password
	 * @param req
	 * @return
	 */
	@RequestMapping("list")
	@ResponseBody
	public ResultMessage list(String username) {

		try {
			// to do
			JqGridRequest request = new JqGridRequest();
			request.setPageable(false);
			request.setSelectColumns("id", "title", "priority_name", "status",
					"cus_user_name", "create_date");
			request.setSort("id", Direction.DESC);

			IcdIncidentController icdIncidentController = ContextHolder
					.getSpringBean(IcdIncidentController.class);

			request.setSearchString(BpmConst.getQueryTaskSqlCondition(
					icdIncidentController.getProceessKey(), "'" + username
							+ "'"));

			List<Map<String, Object>> list = icdIncidentService
					.findAllDetailByRequest(request).getContent();

			return ResultMessage.success(JsonBuilder.buildNormalBinder()
					.toJson(list));

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("获取待办事件列表失败，原因是：" + e.getMessage());
		}

	}

	/**
	 * 获取已办事件列表
	 * 
	 * @param username
	 *            用户名
	 * @param type
	 *            加载方式（1：加载更多，0加载历史）
	 * @param incidentId
	 *            事件id（id具有排序功能）
	 * @param size
	 *            加载数量（默认20）
	 * @return
	 */
	@RequestMapping("listHandled")
	@ResponseBody
	public ResultMessage listHandled(String username, String type,
			String incidentId, Integer size) {

		try {
			// to do
			JqGridRequest request = new JqGridRequest();
			request.setPageable(true);
			request.setRows(size);
			request.setSort("id", Direction.DESC);

			if (type.equalsIgnoreCase("1")
					&& StringUtils.isNotEmpty(incidentId)) {// 加载更多
				request.addFilterRule("id", JqGridFilterRuleOp.lt, incidentId);
			}

			request.setSelectColumns("id", "title", "priority_name", "status",
					"cus_user_name", "create_date");

			IcdIncidentController icdIncidentController = ContextHolder
					.getSpringBean(IcdIncidentController.class);

			request.setSearchString(BpmConst.getQueryMyTaskAttendSqlCondition(
					icdIncidentController.getProceessKey(), username));

			List<Map<String, Object>> list = icdIncidentService
					.findAllDetailByRequest(request).getContent();

			return ResultMessage.success(JsonBuilder.buildNormalBinder()
					.toJson(list));

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("获取已办事件列表失败，原因是：" + e.getMessage());
		}

	}

	/**
	 * 获取事件明细信息
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("incidentDetail")
	@ResponseBody
	public ResultMessage incidentDetail(String id, String username) {
		try {

			JqGridRequest request = new JqGridRequest();

			request.addFilterRule("id", JqGridFilterRuleOp.eq, id);
			request.setSelectColumns("id", "cus_user_id", "cus_user_name",
					"mobile", "cus_customer_name", "cus_email",
					"cus_user_type", "title", "description",
					"service_category_name", "source", "icd_category_name",
					"urgency_name", "effect_name", "priority_name", "slm_name",
					"supporter_name", "reason_analyze", "solution",
					"handle_process", "solver_name", "solution_way",
					"solution_stage", "close_code", "satisfaction",
					"customer_opinion", "are_feedback", "code", "status",
					"project_name", "process_id", "create_date", "assign_date",
					"response_date", "arrival_date", "solved_date");

			Map<String, Object> map = icdIncidentService
					.findOneDetailByRequest(request);
			if (map != null) {

				ConfCiUseRelationService confCiUseRelationService = ContextHolder
						.getSpringBean("confCiUseRelationService");
				JqGridRequest req = new JqGridRequest();
				req.isPageable(false);
				req.addFilterRule("relationId", JqGridFilterRuleOp.eq, id);

				req.setSelectColumns("ci_id");

				List<Map<String, Object>> list = confCiUseRelationService
						.findAllDetailByRequest(req);

				if (list.size() == 1) {
					map.put("ci_id", list.get(0).get("ci_id"));
				} else if (list.size() > 1) {
					map.put("ci_id", "1");
				}

				BpmProcessRunService bpmProcessRunService = ContextHolder
						.getSpringBean("bpmProcessRunService");

				Pair<List<BpmTransitionLine>, Map<String, Object>> p = bpmProcessRunService
						.getNextStepsAndNodeSetting("incidentProcess",
								(String) map.get("process_id"), username);

				String mobileHandleType = null;

				Map<String, Object> nodeSetting = p.getRightObject();
				if (nodeSetting != null) {
					mobileHandleType = (String) nodeSetting
							.get("mobile_handle_type");
				}
				map.put("mobile_handle_type", mobileHandleType);

				if (mobileHandleType != null
						&& !"none".equals(mobileHandleType)) {
					map.put("process_lines", p.getLeftObject());

					AppDictService appDictService = ContextHolder
							.getSpringBean("appDictService");
					JqGridRequest r = new JqGridRequest();
					r.isPageable(false);
					r.setSord("order_num");
					r.setSelectColumns("name");
					r.addFilterRule("type_code", JqGridFilterRuleOp.eq,
							"INCIDENT_SOLUTIONWAY");

					List<AppDict> dicts = appDictService
							.findByType("INCIDENT_SOLUTIONWAY");

					String[] sw = new String[dicts.size()];

					for (int i = 0; i < sw.length; i++) {
						sw[i] = dicts.get(i).getName();
					}

					map.put("solution_ways", sw);
				}

				return ResultMessage.success(JsonBuilder.buildNormalBinder()
						.toJson(map));
			} else {
				return ResultMessage.failure("该事件已删除!");
			}

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("获取事件详情失败，原因是：" + e.getMessage());
		}

	}

	/**
	 * 获取事件服务级别
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("incidentSLA")
	@ResponseBody
	public ResultMessage incidentSLA(String id) {
		try {

			SlmServiceTargetService slmServiceTargetService = ContextHolder
					.getSpringBean(SlmServiceTargetService.class);

			IcdIncident icdIncident = icdIncidentService.findOne(id);
			if (icdIncident != null) {
				List<Map<String, Object>> list = slmServiceTargetService
						.findSlmServiceTargetsValue(icdIncident.getSlmId(), id);
				if (list != null && list.size() > 0) {
					return ResultMessage.success(JsonBuilder
							.buildNormalBinder().toJson(list));
				} else {
					return ResultMessage.failure("该事件尚未关联服务级别");
				}
			} else {
				return ResultMessage.failure("获取事件服务级别失败，该事件已被删除");
			}

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("获取事件服务级别失败，原因是：" + e.getMessage());
		}

	}

	/**
	 * 事件动作接口
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("incidentAction")
	@ResponseBody
	public ResultMessage incidentAction(String id, String username,
			String optType) {
		try {

			IcdIncident icdIncident = icdIncidentService.findOne(id);
			if (icdIncident != null) {

				switch (optType) {
				case "01": // 响应
					icdIncident.setStatus("已响应");
					icdIncident.setResponseDate(new Timestamp(
							new java.util.Date().getTime()));
					break;
				case "02": // 到场
					icdIncident.setStatus("已到场");
					icdIncident.setArrivalDate(new Timestamp(
							new java.util.Date().getTime()));
					break;
				case "03": // 解决
					// icdIncident.setStatus("已解决");
					// Timestamp d = new Timestamp(System.currentTimeMillis());
					// icdIncident.setSolvedDate(d);
					// icdIncident.setSolverId(username);
					break;
				default:
					break;
				}
				icdIncidentService.saveOrUpdate(icdIncident);
				return ResultMessage.success(JsonBuilder.buildNormalBinder()
						.toJson(icdIncident.getStatus()));
			} else {
				return ResultMessage.failure("操作失败，该事件已被删除");
			}

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("操作失败，原因是：" + e.getMessage());
		}

	}

	/**
	 * 事件动作接口
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("incidentSovle")
	@ResponseBody
	public ResultMessage incidentSovle(String id, String reason_analyze,
			String solution, String handle_process, String solver_name,
			String solution_way, String handle_type, String next_tran_id,
			String process_mode) {
		try {

			IcdIncident icdIncident = icdIncidentService.findOne(id);

			if (icdIncident != null) {
				AppUserService appUserService = ContextHolder
						.getSpringBean("appUserService");
				IUser solver = appUserService.findByUsername(solver_name);
				Timestamp d = new Timestamp(System.currentTimeMillis());
				icdIncident.setSolvedDate(d);
				icdIncident.setSolverId(solver_name);
				icdIncident.setSolverName(solver.getFullname());
				icdIncident.setReasonAnalyze(reason_analyze);
				icdIncident.setSolution(solution);
				icdIncident.setHandleProcess(handle_process);
				icdIncident.setSolutionWay(solution_way);
				 

				switch (handle_type) {
				case "1": // 保存
					//icdIncident.setStatus("已解决未提交");
					icdIncidentService.saveOrUpdate(icdIncident);
					break;
				case "2": // 提交

					//icdIncident.setStatus("已解决");
					icdIncidentService.saveOrUpdate(icdIncident);
					BpmProcessRunService bpmProcessRunService = ContextHolder
							.getSpringBean(BpmProcessRunService.class);

					int processMode = 0;

					try {
						processMode = Integer.parseInt(process_mode);
					} catch (Exception e) {

					}

					bpmProcessRunService.gotoNextSetp(solver_name,
							"incidentProcess", null, next_tran_id,
							icdIncident.getProcessId(), icdIncident.getId(),
							null, null, processMode, 0);
					//
					// bpmProcessRunService.complateProcessTask(solver_name,
					// icdIncident.getId(), null, next_tran_id, 0);
					break;

				default:
					break;
				}

				return ResultMessage.success(JsonBuilder.buildNormalBinder()
						.toJson(icdIncident.getStatus()));
			} else {
				return ResultMessage.failure("操作失败，该事件已被删除");
			}

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("操作失败，原因是：" + e.getMessage());
		}

	}

	/**
	 * 获取用户的历史事件
	 * 
	 * @param userId
	 *            用户Id
	 * @param type
	 *            加载方式（1：加载更多，0加载历史）
	 * @param incidentId
	 *            事件id（id具有排序功能）
	 * @param size
	 *            加载数量（默认20）
	 * @return
	 */
	@RequestMapping("historyIncidentByUserId")
	@ResponseBody
	public ResultMessage historyIncidentByUserId(String userId,
			String curIncidentId, Integer currentPage, Integer size) {

		try {
			// to do
			JqGridRequest request = new JqGridRequest();
			request.setPageable(true);
			request.setRows(size);
			request.setPage(currentPage);
			request.setSort("id", Direction.DESC);

			request.addFilterRule("id", JqGridFilterRuleOp.ne, curIncidentId);

			request.addFilterRule("cus_user_id", JqGridFilterRuleOp.eq, userId);

			request.setSelectColumns("id", "title", "priority_name", "status",
					"create_date");

			List<Map<String, Object>> list = icdIncidentService
					.findAllDetailByRequest(request).getContent();

			return ResultMessage.success(JsonBuilder.buildNormalBinder()
					.toJson(list));

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("获取用户历史事件失败，原因是：" + e.getMessage());
		}

	}

	@RequestMapping("historyHandleProcess")
	@ResponseBody
	public ResultMessage historyHandleProcess(String relationId) {
		try {

			if (StringUtils.isEmpty(relationId)) {
				return null;
			}

			IcdIncidentHandleProcessService icdIncidentHandleProcessService = ContextHolder
					.getSpringBean(IcdIncidentHandleProcessService.class);
			JqGridRequest req = new JqGridRequest();
			req.isPageable(false);
			req.addFilterRule("relation_id", JqGridFilterRuleOp.eq, relationId);
			List<IcdIncidentHandleProcess> list = icdIncidentHandleProcessService
					.findAll(req).getContent();
			List<Map<String, Object>> newList = new ArrayList<Map<String, Object>>();
			for (IcdIncidentHandleProcess obj : list) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", obj.getId());
				map.put("reason_analyze", obj.getReasonAnalyze());
				map.put("solution", obj.getSolution());
				map.put("handle_process", obj.getHandleProcess());
				map.put("modifier", obj.getModifier());
				map.put("modify_date", obj.getModifyDate());
				newList.add(map);
			}

			return ResultMessage.success(JsonBuilder.buildNormalBinder()
					.toJson(newList));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("获取历史处理过程失败，原因是：" + e.getMessage());
		}

	}

}
